import { transformRequest, transformResponse } from './helpers/data'
import { processHeaders } from './helpers/headers'
import { AxiosRequestConfig } from './types'

// 为 Axios 类添加默认的配置
const defaults: AxiosRequestConfig = {
  method: 'get',

  timeout: 0,

  headers: {
    common: {
      Accept: 'application/json, text/plain, */*'
    }
  },

  xsrfCookieName: 'XSRF-TOKEN',

  xsrfHeaderName: 'X-XSRF-TOKEN',

  transformRequest: [
    function(data: any, headers: any): any {
      processHeaders(headers, data)
      return transformRequest(data)
    }
  ], // 发送请求前，修改 config 的配置
  transformResponse: [
    function(data: any): any {
      return transformResponse(data)
    }
  ], // 发送请求后，修改 data 的配置

  validateStatus(status: number): boolean {
    return status >= 200 && status < 300
  }
}

// 根据不同的类型的请求，配置不同的 header 属性，
// 后面会对 common 以及各个方法中的属性进行 flatten

// 不带有 request data 的请求
const methodsNoData = ['delete', 'get', 'head', 'options']
methodsNoData.forEach(method => {
  defaults.headers[method] = {}
})

// 带有 request data 的请求
const methodsWithData = ['post', 'put', 'patch']
methodsWithData.forEach(method => {
  defaults.headers[method] = { 'Content-Type': 'application/x-www-form-urlencoded' }
})

export default defaults
